package com.iweb.servlet;

import com.iweb.constant.MyConstant;
import com.iweb.constant.UserAction;
import com.iweb.entity.User;
import com.iweb.service.UserService;
import com.iweb.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author sheng
 * @date 2021/9/19
 * @desc处理后台用户的业务请求
 */
@WebServlet(name="userServlet",urlPatterns = {"/user.do"})
public class UserServlet extends HttpServlet {
  private UserService userService=new UserServiceImpl();


  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String action=req.getParameter("action");
    if(UserAction.LIST.equals(action)){
      //显示列表
      list(req,resp);
      return;
    }
    if(UserAction.REMOVE.equals(action)){
      //删除
      remove(req,resp);
      return;
    }
    if(UserAction.ADD.equals(action)){
      //打开新增界面
      req.getRequestDispatcher(MyConstant.JSPPREFIX+"admin/useradd.jsp").forward(req,resp);
      return;
    }
    if(UserAction.DOADD.equals(action)){
     //处理新增表单
      doAdd(req,resp);
      return;
    }
    if(UserAction.MODIFY.equals(action)){
      modify(req,resp);
      return;
    }
    if(UserAction.DOMODIFY.equals(action)){
      doModify(req,resp);
      return;
    }
  }

  private boolean validateModifyUser(User user,HttpServletRequest req){
    if(user.getId()==null){
      req.setAttribute("userIdErrorMessage","用户标识无效");
      return false;
    }
    if(user.getUserName()==null || user.getUserName().length()==0){
      req.setAttribute("userNameErrorMessage","用户姓名不能为空");
      return false;
    }
    if(user.getSex()==null){
      req.setAttribute("sexErrorMessage","性别不能为空");
      return false;
    }
    if(user.getSex().equals(1) && user.getSex().equals(0)){
      req.setAttribute("sexErrorMessage","性别值不合法");
      return false;
    }
    return true;
  }

  /**
   * 处理修改表单
   * @param req
   * @param resp
   */
  private void doModify(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //获取表单数据
    User user=new User();
    user.setId(Integer.valueOf(req.getParameter("id")));
    user.setLoginName(req.getParameter("loginName"));
    user.setType(Integer.valueOf(req.getParameter("type")));
    user.setSex(Integer.valueOf(req.getParameter("sex")));
    user.setMobile(req.getParameter("mobile"));
    user.setIdentityCode(req.getParameter("identityCode"));
    user.setEmail(req.getParameter("email"));
    user.setUserName(req.getParameter("userName"));
    //服务器端数据校验
    boolean result=this.validateModifyUser(user,req);
    if (!result){
      //校验失败，转发到修改界面，并显示错误信息
      //带上旧的错误的数据
      req.setAttribute("user",user);
      req.getRequestDispatcher(MyConstant.JSPPREFIX+"admin/usermodify.jsp").forward(req,resp);
      return;
    }

    //保存修改用户数据
    try {
      boolean modify=this.userService.modify(user);
      if(modify){
        //进行响应,保存成功后跳转到用户列表
        resp.sendRedirect(req.getContextPath()+"/user.do?action=list");
      }else{
        req.getRequestDispatcher(MyConstant.JSPPREFIX+"404.jsp").forward(req,resp);
        return;
      }
    } catch (Exception e) {
      e.printStackTrace();
      //设置错误信息
      req.setAttribute("errorMessage",e.getMessage());
      //跳转到美化后的错误处理界面
      req.getRequestDispatcher(MyConstant.JSPPREFIX+"500.jsp").forward(req,resp);
    }
  }

  /**
   * 打开修改界面
   * @param req
   * @param resp
   */
  private void modify(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
    //查询数据
    String sid=req.getParameter("id");
    if(sid==null || sid.length()==0){
      req.getRequestDispatcher(MyConstant.JSPPREFIX+"404.jsp").forward(req,resp);
      return;
    }
    try{
      Integer id=Integer.parseInt(sid);
      User user=this.userService.findById(id);
      if(user==null){
        req.getRequestDispatcher(MyConstant.JSPPREFIX+"404.jsp").forward(req,resp);
        return;
      }
      //保存数据
      req.setAttribute("user",user);
      //跳转到修改界面
      req.getRequestDispatcher(MyConstant.JSPPREFIX+"admin/usermodify.jsp").forward(req,resp);

    }catch(Exception e){
      e.printStackTrace();
      //设置错误信息
      req.setAttribute("errorMessage",e.getMessage());
      //跳转到美化后的错误处理界面
      req.getRequestDispatcher(MyConstant.JSPPREFIX+"500.jsp").forward(req,resp);
    }

  }


  /**
   * 处理新增表单
   * @param req
   * @param resp
   */
  private void doAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //获取表单数据
    User user=new User();
    user.setLoginName(req.getParameter("loginName"));
    user.setType(Integer.valueOf(req.getParameter("type")));
    user.setSex(Integer.valueOf(req.getParameter("sex")));
    user.setMobile(req.getParameter("mobile"));
    user.setIdentityCode(req.getParameter("identityCode"));
    user.setEmail(req.getParameter("email"));
    user.setUserName(req.getParameter("userName"));
    //保存用户数据
    try {
      this.userService.add(user);
      //进行响应,保存成功后跳转到用户列表
      resp.sendRedirect(req.getContextPath()+"/user.do?action=list");
    } catch (Exception e) {
      e.printStackTrace();
      //设置错误信息
      req.setAttribute("errorMessage",e.getMessage());
      //跳转到美化后的错误处理界面
      req.getRequestDispatcher(MyConstant.JSPPREFIX+"500.jsp").forward(req,resp);
    }

  }


  /**
   * 删除用户
   * @param req
   * @param resp
   */
  private void remove(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //获取要删除的用户id
    String sid=req.getParameter("id");
    if(sid==null || sid.length()==0){
      req.getRequestDispatcher(MyConstant.JSPPREFIX+"404.jsp").forward(req,resp);
      return;
    }
    //执行删除操作
    try {
      Integer id=Integer.parseInt(sid);
      boolean result=this.userService.remove(id);
      if(result){
        //页面跳转-列表
        resp.sendRedirect(req.getContextPath()+"/user.do?action=list");
      }else{
        req.getRequestDispatcher(MyConstant.JSPPREFIX+"404.jsp").forward(req,resp);
      }

    } catch (Exception e) {
      //设置错误信息
      req.setAttribute("errorMessage",e.getMessage());
      //跳转到美化后的错误处理界面
      req.getRequestDispatcher(MyConstant.JSPPREFIX+"500.jsp").forward(req,resp);
    }
  }

  /**
   * 打开用户列表界面
   * @param req
   * @param resp
   */

  private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {
      //获取用户数据
      List<User> userList=this.userService.findList();
      //保存数据
      req.setAttribute("userList",userList);
      //打开用户列表界面
      req.getRequestDispatcher(MyConstant.JSPPREFIX+"admin/userlist.jsp").forward(req,resp);
    } catch (Exception e) {
      e.printStackTrace();
      //设置错误信息
      req.setAttribute("errorMessage",e.getMessage());
      //跳转到美化后的错误处理界面
      req.getRequestDispatcher(MyConstant.JSPPREFIX+"500.jsp").forward(req,resp);
    }

  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    this.doGet(req, resp);
  }
}
